package ysyh55.android.base.activity;

import android.app.TabActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;

public abstract class BaseTabActivity extends TabActivity implements
OnSharedPreferenceChangeListener {
	private SharedPreferences mPreferences;

	public abstract void onSkinChanged(Resources res);

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
	}

	@Override
	public void onResume() {
		super.onResume();

		mPreferences.registerOnSharedPreferenceChangeListener(this);
		skinChanged(mPreferences.getString("SkinPackageName", getPackageName()));
	}

	public void setCurrentSkinPackage(String skinPackage) {
		SharedPreferences.Editor editor = mPreferences.edit();
		editor.putString("SkinPackageName", skinPackage);
		editor.commit();
	}

	public String getCurrentSkinPackage() {
		return mPreferences.getString("SkinPackageName", getPackageName());
	}

	private void skinChanged(String skinPackage) {
		try {
			Context skinContext = this.createPackageContext(skinPackage,
					CONTEXT_IGNORE_SECURITY);
			onSkinChanged(skinContext.getResources());
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
		if (key.equals("SkinPackageName")) {
			skinChanged(sp.getString("SkinPackageName", getPackageName()));
		}
	}

}
